package com.hutao.medical.controller.statics;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hutao.medical.common.enums.TreatmentTraceEnum;
import com.hutao.medical.common.util.CookieUtils;
import com.hutao.medical.common.util.ExcelUtil;
import com.hutao.medical.common.util.JsonUtils;
import com.hutao.medical.common.util.Params;
import com.hutao.medical.common.util.Result;
import com.hutao.medical.common.util.StringUtil;
import com.hutao.medical.pojo.audit.AuditRecord;
import com.hutao.medical.service.AuditRecordDetailService;
import com.hutao.medical.service.BorrowService;
import com.hutao.medical.service.FirstLevelMedicalService;
import com.hutao.medical.service.MedRecordService;
import com.hutao.medical.service.TreatmentTraceService;

@Controller
@RequestMapping("/statics")
public class StaticsController {
	private Logger log = LoggerFactory.getLogger(StaticsController.class);
	
	@Autowired
	private MedRecordService medRecordService;
	
	@Autowired
	private BorrowService borrowService;
	
	@Autowired
	private FirstLevelMedicalService firstLevelMedicalService;

	@Autowired
	private AuditRecordDetailService auditRecordDetailService;
	

	@Autowired
	private TreatmentTraceService treatmentTraceService;

	private static Object synObject = new Object();

	/**
	 * 跳转到病案归档率页面
	 */
	@RequestMapping("/fileRate")
	public String fileRate() {
		return "statics/fileRate";
	}

	// 医学质量统计导航
	@RequestMapping("/qualitystatistics")
	public String qualityCount() {
		return "statics/statistics/qualitystatistics";
	}

	// 住院病人来源导航
	@RequestMapping("/Sourceofpatients")
	public String inpatient() {
		return "statics/Sourceofpatients/domesticpatient";
	}

	// 住院疾病顺位导航
	@RequestMapping("/inhospitalDisease")
	public String inhospitalDisease() {
		return "statics/diseaseRecord/diagnosisDisease";
	}

	// 首页审核导航
	@RequestMapping("/indexAuditNavigation")
	public String indexAudit() {
		return "statics/indexAudit/operationAudit";
	}

	// 病案首页报告
	@RequestMapping("/indexCaseReport")
	public String indexCaseReport() {
		return "statics/indexCaseReport/indexDataDirectReport";
	}

	/**
	 * 病案借阅查看
	 * 
	 * @return
	 */
	@RequestMapping("/borrowMed")
	public String borrowMed() {
		return "statics/borrowMed";
	}

	/**
	 * 病案借阅
	 * @return
	 */
	@RequestMapping("/borrow")
	public String borrow(Model model,HttpServletRequest request) {
		Map<String, List<java.util.Map<String, Object>>> map=medRecordService.getBaseInfoMap();
		String borrowMan = CookieUtils.getCookieValue(request, "userName");
		if(StringUtils.isNotEmpty(borrowMan)){
			List<Map<String,Object>> borrowedFirstGuidList = borrowService.getBorrowedFirstGuidList(borrowMan);
			System.out.println(borrowedFirstGuidList);
			if(CollectionUtils.isNotEmpty(borrowedFirstGuidList)){
				model.addAttribute("borrowedFirstGuidJson",JsonUtils.objectToJson(borrowedFirstGuidList));
			}else{
				model.addAttribute("borrowedFirstGuidJson",null);
			}
			
		}
		if(MapUtils.isNotEmpty(map)){
			model.addAttribute("officeList",map.get("offices"));
		}
		return "statics/borrow";
	}

	/**
	 * 病案借阅审批
	 * 
	 * @return
	 */
	@RequestMapping("/borrowApprove")
	public String borrowApprove() {
		return "statics/borrowApprove";
	}

	@RequestMapping("/borrowStatics")
	public String borrowStatics(Model model) {
		Map<String, List<java.util.Map<String, Object>>> map=medRecordService.getBaseInfoMap();
		System.out.println("进入");
		if(MapUtils.isNotEmpty(map)){
			model.addAttribute("officeList",map.get("offices"));
		}
		return "statics/borrowStatics";
	}

	@RequestMapping("/unFileMed")
	public String unFileMed() {
		return "statics/unFileMed";
	}

	@RequestMapping("/statisticIndex")
	public String statisticIndex() {
		return "statics/statistic_index";
	}

	@RequestMapping("/medTrace")
	public String medTrace() {
		return "statics/medTrace";
	}

	@RequestMapping("/medTraceList")
	public String medTraceList() {
		return "statics/medTraceList";
	}

	@RequestMapping("/medShelve")
	public String medShelve() {
		return "statics/medShelve";
	}

	/**
	 * 导出excel
	 * 
	 * @param params
	 * @return
	 */
	@RequestMapping("/exportFileExcel")
	public void exportExcel(Params params, HttpServletResponse response) {
		List<Map<String, Object>> scanWorkMapList = new ArrayList<>();

		try {
			response.setContentType("octets/stream");
			String excelName = "2017-05-01 -- 2017-5-31归档率报表";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();

			// 查询数据
			scanWorkMapList = this.generateData();
			String[] bases = { "String", "String", "String", "String", "String", "String", "String" };
			String title = "2017-05-01 -- 2017-5-31归档率报表";
			String[] header = { "标识码", "病案号", "姓名", "出院科室", "出院日期", "归档日期", "迟送天数" };
			ExcelUtil.exportExcel(out, title, bases, header, scanWorkMapList);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	public List<Map<String, Object>> generateData() {
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map1 = new LinkedHashMap<>();
		map1.put("onlyId", "1-10525858");
		map1.put("mrId", "6163543");
		map1.put("name", "李靖环");
		map1.put("office", "乳腺甲状腺外科病房[中心院区]");
		map1.put("outDate", "2017-05-26");
		map1.put("fileDate", "2017-06-01");
		map1.put("delayDays", "3");
		list.add(map1);

		Map<String, Object> map2 = new LinkedHashMap<>();
		map2.put("onlyId", "1-10524647");
		map2.put("mrId", "6277411");
		map2.put("name", "陶书亮");
		map2.put("office", "创伤急症外科病房[中心院区]");
		map2.put("outDate", "2017-05-26");
		map2.put("fileDate", "2017-06-01");
		map2.put("delayDays", "3");
		list.add(map2);

		Map<String, Object> map3 = new LinkedHashMap<>();
		map3.put("onlyId", "1-10525900");
		map3.put("mrId", "1100411");
		map3.put("name", "朱远学");
		map3.put("office", "泌尿外科病房[中心院区]");
		map3.put("outDate", "2017-05-26");
		map3.put("fileDate", "2017-06-01");
		map3.put("delayDays", "3");
		list.add(map3);

		Map<String, Object> map4 = new LinkedHashMap<>();
		map4.put("onlyId", "2-10219285");
		map4.put("mrId", "6253074");
		map4.put("name", "王彦杰");
		map4.put("office", "手足外科病房[中心院区]");
		map4.put("outDate", "2017-05-25");
		map4.put("fileDate", "2017-05-31");
		map4.put("delayDays", "3");
		list.add(map4);

		Map<String, Object> map5 = new LinkedHashMap<>();
		map5.put("onlyId", "1-10524967");
		map5.put("mrId", "6277708");
		map5.put("name", "刘成兰");
		map5.put("office", "妇科西病房[中心院区]");
		map5.put("outDate", "2017-05-25");
		map5.put("fileDate", "2017-05-31");
		map5.put("delayDays", "3");
		list.add(map5);

		Map<String, Object> map6 = new LinkedHashMap<>();
		map6.put("onlyId", "2-10233475");
		map6.put("mrId", "6276839");
		map6.put("name", "丁李兵");
		map6.put("office", "东院手足外科一病房[东院区]");
		map6.put("outDate", "2017-05-25");
		map6.put("fileDate", "2017-05-31");
		map6.put("delayDays", "3");
		list.add(map6);

		Map<String, Object> map7 = new LinkedHashMap<>();
		map7.put("onlyId", "1-10524005");
		map7.put("mrId", "6276799");
		map7.put("name", "刘西顺");
		map7.put("office", "泌尿外科病房[中心院区]");
		map7.put("outDate", "2017-05-25");
		map7.put("fileDate", "2017-05-31");
		map7.put("delayDays", "3");
		list.add(map7);

		Map<String, Object> map8 = new LinkedHashMap<>();
		map8.put("onlyId", "1-10524873");
		map8.put("mrId", "6259044");
		map8.put("name", "樊英丽");
		map8.put("office", "乳腺甲状腺外科病房[中心院区]");
		map8.put("outDate", "2017-05-24");
		map8.put("fileDate", "2017-05-31");
		map8.put("delayDays", "4");
		list.add(map8);

		Map<String, Object> map9 = new LinkedHashMap<>();
		map9.put("onlyId", "1-10522853");
		map9.put("mrId", "6275686");
		map9.put("name", "高树珍");
		map9.put("office", "保健综合二病房（耳鼻咽喉科）[中心院区]");
		map9.put("outDate", "2017-05-24");
		map9.put("fileDate", "2017-05-31");
		map9.put("delayDays", "4");
		list.add(map9);

		Map<String, Object> map10 = new LinkedHashMap<>();
		map10.put("onlyId", "1-10524695");
		map10.put("mrId", "6277461");
		map10.put("name", "汪琦");
		map10.put("office", "产科病房[中心院区]");
		map10.put("outDate", "2017-05-22");
		map10.put("fileDate", "2017-05-26");
		map10.put("delayDays", "4");
		list.add(map10);

		return list;
	}

	/**
	 * 病案归档审核
	 * 
	 * @return
	 */
	@RequestMapping("/medFileCheck")
	public String medFileCheck(Model model) {
		Map<String, List<java.util.Map<String, Object>>> map=medRecordService.getBaseInfoMap();
		if(MapUtils.isNotEmpty(map)){
			model.addAttribute("officeList",map.get("offices"));
		}
		return "statics/medFileCheck";
	}

	// 病案审核审核页面
	@RequestMapping("/medFileCheck_detail")
	public String medFileCheck_detail(@RequestParam("firstGuid") String firstGuid, HttpServletRequest request,
			Map<String, Object> resultValueMap) {
		Map<String, Object> firstLevelMedical = firstLevelMedicalService.findFirstLevelMedicalByFirstGuid(firstGuid);
		resultValueMap.put("firstLevelMedical", firstLevelMedical);

		synchronized (synObject) {
			long count = treatmentTraceService.findCountByFirstGuidAndTraceTypeId(firstGuid,
					TreatmentTraceEnum.MEDICAL_RECORD_AUDIT.getValue());

			if (StringUtil.isNotBlank(firstGuid) && count == 0) {
				// 添加审核示踪记录
				String currentUser = CookieUtils.getCookieValue(request, "TT_TOKEN");
				Map<String, Object> params = new HashMap<>();
				params.put("firstGuid", firstGuid);
				params.put("loginName", currentUser);
				params.put("traceTypeId", TreatmentTraceEnum.MEDICAL_RECORD_AUDIT.getValue());
				params.put("traceInfo", null);
				treatmentTraceService.insertTreatmentTrace(params);
			}
		}

		return "statics/medFileCheck_detail";
	}

	// 病案审核审核页面
	@RequestMapping("/auditDetail")
	public String auditDetail(@RequestParam("firstGuid") String firstGuid,
			@RequestParam("auditDicId") Integer auditDicId, HttpServletRequest request, Model model) throws Exception {
		Map<String, Object> firstLevelMedical = firstLevelMedicalService.findFirstLevelMedicalByFirstGuid(firstGuid);
		model.addAttribute("firstLevelMedical", firstLevelMedical);
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		//拼装保存参数
		AuditRecord auditRecord = auditRecordDetailService.appendAuditRecord(auditDicId);
		System.out.println("firstGuid="+firstGuid);
		//保存审核详情
		auditRecordDetailService.insertAuditRecordDetail(firstGuid, currentUser, auditRecord, firstLevelMedical);
		List<Map<String, Object>> auditRecordDetailList = auditRecordDetailService
				.findAuditDetailByFirstGuid(firstGuid);
		model.addAttribute("auditRecordDetailList", auditRecordDetailList);
		for (Map<String, Object> map : auditRecordDetailList) {
			System.out.println(map);
		}
		synchronized (synObject) {
			long count = treatmentTraceService.findCountByFirstGuidAndTraceTypeId(firstGuid,
					TreatmentTraceEnum.MEDICAL_RECORD_AUDIT.getValue());

			if (StringUtil.isNotBlank(firstGuid) && count == 0) {
				// 添加审核示踪记录
				Map<String, Object> params = new HashMap<>();
				params.put("firstGuid", firstGuid);
				params.put("loginName", currentUser);
				params.put("traceTypeId", TreatmentTraceEnum.MEDICAL_RECORD_AUDIT.getValue());
				params.put("traceInfo", null);
				treatmentTraceService.insertTreatmentTrace(params);
			}
		}

		return "statics/indexAudit/Audit_detail";
	}

	/**
	 * 导出Excel
	 * 
	 * @param params
	 * @return
	 */
	@RequestMapping("/exportCheckExcel")
	public void exportCheckExcel(Params params, HttpServletResponse response) {
		List<Map<String, Object>> scanWorkMapList = new ArrayList<>();

		try {
			response.setContentType("octets/stream");
			String excelName = "审核报表";
			// 转码防止乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			// 通过response获取文件输出流
			OutputStream out = response.getOutputStream();

			// 查询数据
			scanWorkMapList = this.generateData1();
			// String[] bases={"String","String","String","String","String"};
			String[] bases = { "String", "String", "String", "Date", "Double" };
			String title = "审核报表";
			String[] header = { "标识码", "病案号", "姓名", "出院日期", "离院方式" };
			ExcelUtil.exportExcel(out, title, bases, header, scanWorkMapList);

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	@RequestMapping("/medCatalogCheck")
	public String medCatalogCheck() {
		return "statics/medCatalogCheck";
	}

	public List<Map<String, Object>> generateData1() {
		List<Map<String, Object>> list = new ArrayList<>();

		Map<String, Object> map1 = new LinkedHashMap<>();
		map1.put("onlyId", null);
		map1.put("mrId", "刘东亮");
		map1.put("name", "李靖环");
		// map1.put("office","2017-08-23");
		map1.put("office", new Date());
		// map1.put("outDate","医嘱");
		map1.put("outDate", null);
		list.add(map1);

		Map<String, Object> map2 = new LinkedHashMap<>();
		map2.put("onlyId", "1-6277554");
		map2.put("mrId", "6277554");
		map2.put("name", "李桂英");
		// map2.put("office","2017-06-01");
		map2.put("office", new Date());
		// map2.put("outDate","医嘱");
		map2.put("outDate", 1.24);
		list.add(map2);

		Map<String, Object> map3 = new LinkedHashMap<>();
		map3.put("onlyId", "1-6280073");
		map3.put("mrId", "6280073");
		map3.put("name", "郑加田");
		// map3.put("office","2017-06-01");
		map3.put("office", new Date());
		// map3.put("outDate","医嘱 ");
		map3.put("outDate", 1.25);
		list.add(map3);

		Map<String, Object> map4 = new LinkedHashMap<>();
		map4.put("onlyId", "1-6239425");
		map4.put("mrId", "6239425");
		map4.put("name", "杨远立");
		// map4.put("office","2017-01-01");
		map4.put("office", new Date());
		// map4.put("outDate","医嘱 ");
		map4.put("outDate", 1.24);
		list.add(map4);

		Map<String, Object> map5 = new LinkedHashMap<>();
		map5.put("onlyId", "1-6240433");
		map5.put("mrId", "6240433");
		map5.put("name", "张洋");
		// map5.put("office","2017-01-01");
		map5.put("office", new Date());
		// map5.put("outDate","医嘱 ");
		map5.put("outDate", 1.24);
		list.add(map5);

		Map<String, Object> map6 = new LinkedHashMap<>();
		map6.put("onlyId", "1-867751");
		map6.put("mrId", "867751");
		map6.put("name", "孔祥东");
		// map6.put("office","2011-09-25");
		map6.put("office", new Date());
		// map6.put("outDate","医嘱");;
		map6.put("outDate", 1.24);
		list.add(map6);

		return list;
	}

	@RequestMapping("/requestGet")
	public String requestGet() {
		return "statics/getRequest";
	}

	// 病案审核查询
	@RequestMapping("/medFileCheck_Search")
	public String medFileCheck_Search() {
		return "statics/medFileCheck_Search";
	}

	// 病案审核查询查看详情页面
	@RequestMapping("/medFileCheck_Search_detail")
	public String medFileCheck_Search_detail(@RequestParam("firstGuid") String firstGuid,
			Map<String, Object> resultValueMap) {
		Map<String, Object> firstLevelMedical = firstLevelMedicalService.findFirstLevelMedicalByFirstGuid(firstGuid);
		resultValueMap.put("firstLevelMedical", firstLevelMedical);
		return "statics/medFileCheck_Search_detail";
	}

	// 病案返修查询页面
	@RequestMapping("/medFileRework_Search")
	public String medFileRework_Search(Model model) {
		Map<String, List<java.util.Map<String, Object>>> map=medRecordService.getBaseInfoMap();
		if(MapUtils.isNotEmpty(map)){
			model.addAttribute("officeList",map.get("offices"));
		}
		return "statics/medFileRework_Search";
	}

	// 病案返修查询页面
	@RequestMapping("/medFileRework_Search_detail")
	public String medFileRework_Search_detail(@RequestParam("firstGuid") String firstGuid,
			Map<String, Object> resultValueMap) {
		Map<String, Object> firstLevelMedical = firstLevelMedicalService.findFirstLevelMedicalByFirstGuid(firstGuid);
		resultValueMap.put("firstLevelMedical", firstLevelMedical);
		return "statics/medFileRework_Search_detail";
	}
	
	/**
	 * 移动端病案借阅
	 * 
	 * @param request
	 * @return
	 */
	@PostMapping("/getMedicalBorrowByBorrowMan")
	@ResponseBody
	public Result getMedicalBorrowByBorrowMan(HttpServletRequest request) {
		try {
			String borrowMan = request.getParameter("borrowMan");
			log.info("--------------------借阅人--" + borrowMan);
			List<Map<String,Object>> borrowedFirstGuidList = null;
			
			if (StringUtils.isNotBlank(borrowMan)) {
				borrowedFirstGuidList = borrowService.getBorrowedFirstGuidList(borrowMan);
			}
			
			return new Result(true, "查询成功!", borrowedFirstGuidList, 200);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("移动端病案借阅异常---" + e);
			return new Result(false, "查询失败!", null, 500);
		}
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	

}
